import React, { PureComponent,Fragment } from 'react';
import { findDOMNode } from 'react-dom';
import moment from 'moment';
import { connect } from 'dva';
import {
  List,
  Card,
  Row,
  Col,
  Radio,
  Input,
  Progress,
  Button,
  Icon,
  Dropdown,
  Menu,
  Avatar,
  Modal,
  Form,
  DatePicker,
  Select,
  Badge,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Result from '@/components/Result';
import DescriptionList from '@/components/DescriptionList';
const { Description } = DescriptionList;

import styles from './BasicList.less';

const FormItem = Form.Item;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const SelectOption = Select.Option;
const { Search, TextArea } = Input;
const statusStr = ["无","挂单","买家确认","卖家确认","完成","退款给买家","退款给卖家"]
const itemType = ["-","-","-","-","红水晶","蓝水晶"]
@connect(({ list, loading }) => ({
  list,
  loading: loading.models.list,
}))
@Form.create()
class CardList extends PureComponent {
  state = { visible: false, done: false , selectedRows: [], page:1};

  columns = [
    {
      title: '订单id',
      dataIndex: 'id',
    },

    {
      title: '卖家id',
      dataIndex: 'buyer_id',
    },
    {
      title: '卖家用户名称',
      dataIndex: 'nick',
    },

    {
      title: '买家用户名称',
      dataIndex: 'buyer_name',
    },
    {
      title: '买家id',
      dataIndex: 'seller_id',
    },

    {
      title: '订单当前状态',
      dataIndex: 'status',
      render(val) {
        return <Badge status= {"default"} text={statusStr[val]} />;
        },
    },


    {
      title: '物品',
      dataIndex: 'item_type',
      render(val) {
        return <Badge status={"default"} text={itemType[val]} />;
      },
    },


    {
      title: '数量',
      dataIndex: 'item_num',
    },



    {
      title: '创建时间',
      dataIndex: 'time',
      sorter: true,
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '操作',
      render: (text, record) => (
        <Row>
          <Col>
            <Fragment>
              <a onClick={() => this.showEditModal(record)}>订单处理</a>
            </Fragment>,
          </Col>
        </Row>
      ),
    },
  ];

  formLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 13 },
  };


  componentDidMount() {
    const { dispatch } = this.props;

    dispatch({
      type: 'list/fetch',
      payload: {
        current: 1,
      }
    })

    dispatch({
      type: 'list/ticketFetch',
      payload: {
        current: 1,
      }
    })
  }



  showEditModal = item => {
    this.setState({
      visible: true,
      current: item,
    });
  };

  handleDone = () => {
    this.setState({
      done: false,
      visible: false,
    });
  };

  handleCancel = () => {
    // setTimeout(() => this.addBtn.blur(), 0);
    this.setState({
      visible: false,
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { current,page } = this.state;
    const id = current ? current.id : '';

    console.log("id",id)
    console.log("current",current)
    console.log("page",page)

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        done: true,
      });
      dispatch({
        type: 'list/submit',
        payload: { id,status :fieldsValue.newstatus,current:page},
      });
    });
  };


  handleSubmitTicket = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;

    console.log("handleSubmitTicketStatus handleSubmitTicketStatus")
    form.validateFields((err, fieldsValue) => {
      console.log("handleSubmitTicketStatus err",err)
      if (err) return;

      console.log("handleSubmitTicketStatus",fieldsValue)
      dispatch({
        type: 'list/submitTicket',
        payload: { status :fieldsValue.target},
      });
    });
  };

  handleUpdateMaxValue = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;

    console.log("handleSubmitTicketStatus handleSubmitTicketStatus")
    form.validateFields((err, fieldsValue) => {
      console.log("handleSubmitTicketStatus err",err)
      if (err) return;

      console.log("handleSubmitTicketStatus",fieldsValue)
      dispatch({
        type: 'list/submitmaxValue',
        payload: { status :fieldsValue.maxValue},
      });
    });
  };

  deleteItem = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'list/submit',
      payload: { id },
    });
  };


  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    console.log("ddddddddddddddddddd",formValues)
    console.log("filtersArg",filtersArg)
    console.log("pagination",pagination)
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});
    console.log("filters",filters)
    const params = {
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    this.setState({
      page : pagination.current
    })

    dispatch({
      type: 'list/fetch',
      payload: params,
    });
  };

  render() {
    const {
      list: { list },
      list: { TicketStatus },
      loading,
    } = this.props;
    let data = list
    const { form } = this.props;

    console.log("dddddddddddddddddd",list)
    console.log("TicketStatus ",TicketStatus)
    console.log(" this.props ", this.props)
    const { selectedRows } = this.state;
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { visible, done, current = {} } = this.state;

    const editAndDelete = (key, currentItem) => {
      if (key === 'edit') this.showEditModal(currentItem);
      else if (key === 'delete') {
        Modal.confirm({
          title: '删除任务',
          content: '确定删除该任务吗？',
          okText: '确认',
          cancelText: '取消',
          onOk: () => this.deleteItem(currentItem.id),
        });
      }
    };

    const modalFooter = done
      ? { footer: null, onCancel: this.handleDone }
      : { okText: '保存', onOk: this.handleSubmit, onCancel: this.handleCancel };



    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      pageSize: 7,
      total: 50,
    };


    const getModalContent = () => {
      console.log("current is is:",current)
      if (done) {
        return (
          <Result
            type="success"
            title="操作成功"
            description=""
            actions={
              <Button type="primary" onClick={this.handleDone}>
                确定
              </Button>
            }
            className={styles.formResult}
          />
        );
      }
      return (
        <Form onSubmit={this.handleSubmit}>
          <FormItem label="状态" {...this.formLayout}>
            {getFieldDecorator('newstatus')(
              <Select placeholder="请选择">
                <SelectOption value="5"> 退还给买家</SelectOption>
                <SelectOption value="6"> 退还给卖家 </SelectOption>
              </Select>
            )}
          </FormItem>
        </Form>
      );
    };

    return (
      <PageHeaderWrapper>
        <div className={styles.standardList}>
          <Card
            className={styles.listCard}
            bordered={false}
            title="收徒券是否使用"
            style={{ marginTop: 24 }}
            bodyStyle={{ padding: '0 32px 40px 32px' }}
            // extra={extraContent}
          >
            <Form onSubmit={this.handleSubmitTicket} >
            <Row gutter={{ md: 24, lg: 24, xl: 24 }}>

              <Col md={4} sm={12}>
                <Description term="当前状态："> {TicketStatus==1?"使用":"不使用"} </Description>
              </Col>

              <Col md={8} sm={24}>
                <FormItem   {...this.formLayout} label="修改状态">
                  {form.getFieldDecorator('target', {
                    initialValue: "",
                  })(
                    <Select style={{ width: '100%' }}>
                      <Option  value="1">使用</Option>
                      <Option  value="0">不使用</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>

              <Col md={8} sm={24}>
                <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </span>
              </Col>
            </Row>
            </Form>
          </Card>



          {/*<Card*/}
            {/*className={styles.listCard}*/}
            {/*bordered={false}*/}
            {/*title="角色封号阀值"*/}
            {/*style={{ marginTop: 24 }}*/}
            {/*bodyStyle={{ padding: '0 32px 40px 32px' }}*/}
            {/*// extra={extraContent}*/}
          {/*>*/}
            {/*<Form onSubmit={this.handleUpdateMaxValue} >*/}
              {/*<Row gutter={{ md: 24, lg: 24, xl: 24 }}>*/}

                {/*<Col md={4} sm={12}>*/}
                  {/*<Description term="当前阀值为："> {100} </Description>*/}
                {/*</Col>*/}

                {/*<Col md={8} sm={24}>*/}
                  {/*<FormItem   {...this.formLayout} label="修改阀值">*/}
                    {/*{form.getFieldDecorator('maxValue', {*/}
                      {/*initialValue: "",*/}
                    {/*})(*/}
                     {/*(<Input placeholder="请输入新的阀值" />)*/}
                    {/*)}*/}
                  {/*</FormItem>*/}
                {/*</Col>*/}

                {/*<Col md={8} sm={24}>*/}
                {/*<span className={styles.submitButtons}>*/}
              {/*<Button type="primary" htmlType="submit">*/}
                {/*确定*/}
              {/*</Button>*/}
            {/*</span>*/}
                {/*</Col>*/}
              {/*</Row>*/}
            {/*</Form>*/}
          {/*</Card>*/}


          <Card
            className={styles.listCard}
            bordered={false}
            title="交易列表"
            style={{ marginTop: 24 }}
            bodyStyle={{ padding: '0 32px 40px 32px' }}
            // extra={extraContent}
          >


            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />



          </Card>
        </div>
        <Modal
          title={done ? null : `修改状态`}
          className={styles.standardListForm}
          width={640}
          bodyStyle={done ? { padding: '72px 0' } : { padding: '28px 0 0' }}
          destroyOnClose
          visible={visible}
          {...modalFooter}
        >
          {getModalContent()}
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default CardList;
